<template>
	<view class="">
		<!-- 顶部导航 -->
		<fa-navbar title="充值余额"></fa-navbar>
		<view class="u-p-l-30 u-p-t-50 u-font-30">充值余额</view>
		<view class="u-p-30" v-if="config.rechargetips"><u-alert-tips type="warning" :description="config.rechargetips"></u-alert-tips></view>
		<view class="">
			<u-grid :col="3" :border="false">
				<u-grid-item v-for="(item, index) in moneylist" :key="index">
					<view class="fa-grid">
						<u-button
							throttle-time="0"
							type="primary"
							hover-class="none"
							:custom-style="{ backgroundColor: btnBgColor(item.check), color: btnColor(item.check), border: '1px solid ' + theme.faBorderColor }"
							@click="selectMoney(item.value, index)"
							v-text="item.key"
						></u-button>
					</view>
				</u-grid-item>
				<u-grid-item v-if="config.iscustommoney == 1">
					<view class="u-flex u-row-center fa-grid">
						<input
							type="text"
							class="custom"
							:style="[
								{
									color: theme.bgColor,
									backgroundColor: 'rgb(255, 255, 255)',
									border: '1px solid' + theme.bgColor
								}
							]"
							:value="custom_money"
							@focus="inputInput"
							@blur="inputInput"
							@input="inputInput"
						/>
					</view>
				</u-grid-item>
			</u-grid>
		</view>
		<view class="u-p-l-30 u-p-t-30 u-font-30">选择支付方式</view>

		<view class="u-m-t-30">
			<u-radio-group v-model="paytype" style="width: 100%;">
				<u-cell-item
					v-for="(item, index) in payList"
					:icon="item == 'wechat' ? 'weixin-circle-fill' : 'zhifubao-circle-fill'"
					:key="index"
					:icon-style="{ color: item == 'wechat' ? '#40BA49' : '#00AAEE' }"
					:arrow="false"
					:title="item == 'wechat' ? '微信支付' : '支付宝支付'"
					@click="selectPayType(item)"
				>
					<u-radio :active-color="theme.bgColor" slot="right-icon" :name="item"></u-radio>
				</u-cell-item>
			</u-radio-group>
		</view>
		<view class="u-p-30 u-m-t-60">
			<u-button hover-class="none" type="primary" :custom-style="{ backgroundColor: theme.bgColor, color: theme.color }" @click="submit">立即充值</u-button>
		</view>
		<u-modal v-model="show" :content="content" @confirm="confirm" confirm-text="返回"></u-modal>
		<!-- 底部导航 -->
		<fa-tabbar></fa-tabbar>
	</view>
</template>

<script>
import { login } from '@/common/fa.mixin.js';
export default {
	mixins: [login],
	onLoad() {
		this.getRechargeConfig();
	},
	computed: {
		isWeixin() {
			return this.$util.isWeiXinBrowser();
		}
	},
	watch: {
		money(newValue, oldValue) {
			if (newValue) {
				this.moneylist.forEach((item, index) => {
					item.check = false;
					if (item.value == newValue) {
						item.check = true;
					}
				});
			}
		}
	},
	data() {
		return {
			show: false,
			content: '请检查是否安装好充值插件哦！',
			config: {},
			paytype: 'wechat',
			custom_money: '自定义',
			money: 0,
			moneylist: [],
			payList: []
		};
	},
	methods: {
		inputInput(e) {
			if (e.type == 'blur') {
				this.custom_money = !e.detail.value ? '自定义' : e.detail.value;
				return;
			}
			if (e.type == 'focus') {
				this.custom_money = e.detail.value == '自定义' ? '' : e.detail.value;
				return;
			}
			this.money = e.detail.value;
			this.custom_money = e.detail.value;
		},
		selectMoney(value, index) {
			this.money = value;
		},
		selectPayType(item) {
			this.paytype = item;
		},
		getRechargeConfig: async function() {
			let res = await this.$api.getRechargeConfig();
			if (!res.code) {
				this.show = true;
				return;
			}
			this.config = res.data;
			let list = res.data.moneylist;
			this.moneylist = [];
			for (let i in list) {
				this.moneylist.push({
					key: i,
					value: list[i],
					check: false
				});
			}
			this.money = res.data.defaultmoney;
			this.paytype = res.data.defaultpaytype;
			let payList = res.data.paytypelist.split(',');
			payList.forEach(item => {
				// #ifdef MP-WEIXIN
				if (item == 'wechat') {
					this.payList.push(item);
				}
				// #endif

				// #ifndef MP-WEIXIN
				if (this.$util.isWeiXinBrowser()) {
					if (item == 'wechat') {
						this.payList.push(item);
					}
				} else {
					this.payList.push(item);
				}
				// #endif
			});
		},
		confirm() {
			this.$Router.back(1);
		},
		// #ifndef H5
		async submit() {
			if (this.money < this.config.minmoney) {
				this.$u.toast(`最低充值金额为${this.config.minmoney}元`);
				return;
			}

			let data = {
				money: this.money,
				paytype: this.paytype
			};

			// #ifdef APP-PLUS
			data.appid = plus.runtime.appid;
			data.method = 'app';
			// #endif

			// #ifdef MP-WEIXIN
			data.method = 'miniapp';
			// #endif

			let res = await this.$api.goRechargeSubmit(data);

			if (!res.code) {
				this.$u.toast(res.msg);
				return;
			}

			if (res.data == 'bind') {
				// #ifdef MP-WEIXIN
				this.$wanlshop.to('/pages/community/login/wxlogin');
				// #endif
				return;
			}

			// #ifdef MP-WEIXIN
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: res.data.timeStamp,
				nonceStr: res.data.nonceStr,
				package: res.data.package,
				signType: res.data.signType,
				paySign: res.data.paySign,
				success: res => {
					this.$u.toast('充值成功！');
				},
				fail: err => {
					this.$u.toast('fail:' + JSON.stringify(err));
				}
			});
			// #endif

			// #ifdef APP-PLUS
			uni.requestPayment({
				provider: this.paytype == 'alipay' ? 'alipay' : 'wxpay',
				orderInfo: res.data, //微信、支付宝订单数据
				success: res => {
					this.$u.toast('支付成功！');
				},
				fail: function(err) {
					console.log('fail:' + JSON.stringify(err));
				}
			});
			// #endif
		},
		// #endif
		// #ifdef H5
		submit: async function() {
			if (this.money < this.config.minmoney) {
				this.$u.toast(`最低充值金额为${this.config.minmoney}元`);
				return;
			}
			let data = {
				money: this.money,
				paytype: this.paytype,
				method: 'wap'
			};
			//在微信环境，且为微信支付
			if (this.isWeixin && this.paytype == 'wechat') {
				data.method = 'mp';
				let res = await this.$api.goRechargeSubmit(data);
				if (!res || !res.code) {
					this.$u.toast(res.msg || '支付错误');
					return;
				}
				if (res.data == 'bind') {
					this.goToAuth();
					return;
				}
				window.WeixinJSBridge.invoke(
					'getBrandWCPayRequest',
					{
						appId: res.data.appId, // 公众号名称，由商户传入
						timeStamp: res.data.timeStamp, // 时间戳，自1970年以来的秒数
						nonceStr: res.data.nonceStr, // 随机串
						package: res.data.package,
						signType: res.data.signType, // 微信签名方式：
						paySign: res.data.paySign // 微信签名
					},
					res => {
						if (res.err_msg === 'get_brand_wcpay_request:ok') {
							this.$u.toast('充值成功！');
						} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
							this.$u.toast('取消支付');
						} else {
							this.$u.toast('支付失败');
						}
					}
				);
			} else {
				//非微信环境的wap 支付方法，会返回orderid，再模拟表单提交
				data.returnurl = window.location.href;
				let res = await this.$api.goRechargeSubmit(data);
				if (!res || !res.code) {
					this.$u.toast(res.msg || '支付错误！');
					return;
				}

				//URL地址
				if (res.data.toString().match(/^((?:[a-z]+:)?\/\/)(.*)/i)) {
					location.href = res.data;
					return;
				}

				//Form表单
				document.getElementsByTagName('body')[0].innerHTML = res.data;
				let form = document.querySelector('form');
				if (form && form.length > 0) {
					form.submit();
					return;
				}

				//Meta跳转
				let meta = document.querySelector('meta[http-equiv="refresh"]');
				if (meta && meta.length > 0) {
					setTimeout(function() {
						location.href = meta.content.split(/;/)[1];
					}, 300);
					return;
				}
			}
		}
		// #endif
	}
};
</script>

<style>
.custom {
	text-align: center;
	height: 80rpx;
	border-radius: 5px;
	font-size: 30rpx;
}
.fa-grid {
	width: 100%;
	padding: 0 20rpx;
}
</style>
